package manager;

import Database.Connectmysql;

import javax.swing.*;
import javax.xml.crypto.Data;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

public class AddBook extends JFrame {
    private JLabel lblBookName;
    private JLabel lblAuthor;
    private JTextField bookName ;
    private JTextField author;
    private JButton addBook;
    public AddBook() {
        setTitle("添加图书");
        setBounds(300, 100, 500, 400);
        setLayout(null);
        lblBookName = new JLabel("书名");
        lblAuthor = new JLabel("作者");
        bookName = new JTextField(30);
        author = new JTextField(30);
        addBook = new JButton("添加");

        lblBookName.setBounds(80, 30, 200, 30);
        lblAuthor.setBounds(80, 80, 200, 30);
        bookName.setBounds(200, 30, 200, 30);
        author.setBounds(200, 80, 200, 30);
        addBook.setBounds(200, 300, 80, 30);

        add(lblBookName);
        add(lblAuthor);
        add(bookName);
        add(author);
        add(addBook);

        addBook.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int bookid = 0;
                String bookNameText = bookName.getText();
                String authorText = author.getText();
                LocalDateTime time = LocalDateTime.now();

                Connectmysql cmysql = new Connectmysql(
                        "jdbc:mysql://localhost:3306/bookmanagement",
                        "root",
                        "root",
                        "com.mysql.cj.jdbc.Driver");
                try {
                    if(cmysql.open()){

                        ResultSet rst= cmysql.executeSql(
                                "select max(bookid) from book;",
                                new Object[]{}
                        );
                        if(rst.next()){
                            bookid = rst.getInt(1)+1;
                        }
                        cmysql.executeSqlUpdate("insert into book values (?,?,?,?,?)", new Object[]{bookid,bookNameText,authorText,time,"无人借阅"});
                        System.out.println("添加成功！");
                        setVisible(false);
                        rst.close();
                    }
                } catch (ClassNotFoundException f) {
                    f.printStackTrace();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        });
        setVisible(true);
    }

    public static void main(String[] args) {
        new AddBook();
    }
}
